package com.sunday.common.http.apache;

import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 连接管理
 * @Author: zsy
 * @Create: 2022/10/17 11:42
 */
@Slf4j
@Deprecated
public class IdleConnectionManager {

    //线程终止开关
    protected volatile boolean running = false;
    //守护线程
    protected Thread.UncaughtExceptionHandler handler = (t, e) -> log.error("parse events has an error : {}", e.toString(), e);
    //启动线程
    protected Thread thread = null;
    //http连接管理器
    private final HttpClientConnectionManager manager;
    //存活时间
    private final int timeToLive;
    //时间类型
    private final TimeUnit unit;

    public IdleConnectionManager(HttpClientConnectionManager manager, int timeToLive, TimeUnit unit) {
        this.manager = manager;
        this.timeToLive = timeToLive;
        this.unit = unit;
    }

    public void start() {
        thread = new Thread(() -> process());
        thread.setUncaughtExceptionHandler(handler);
        running = true;
        thread.start();
    }

    public void stop() {
        if (!running) {
            return;
        }
        log.info("{}", "[停止]连接驱逐策略");
        running = false;
        if (thread != null) {
            try {
                thread.join();//等待该线程死亡
            } catch (InterruptedException e) {
                // ignore
            }
        }
    }

    public void process() {
        log.info("{}", "[启动]连接驱逐策略");
        while (running) {
            try {
                unit.sleep(timeToLive / 2);
                /**
                 * Close expired connections
                 * 清理一次失效的connection
                 * 依赖connTimeToLive参数以及keep alive strategy设置的
                 */
//                manager.closeExpiredConnections();
//                manager.upgrade();
                /**
                 * 可选，关闭连接
                 * 空闲时间超过30秒
                 */
//                manager.closeIdleConnections(timeToLive, unit);
            } catch (Exception e) {
                log.error("{}", "[异常]连接驱逐策略 : {}", e.toString(), e);
            }
        }
        log.info("{}", "=================== 连接驱逐策略 -> 服务已停止 ===================");
    }

    public static IdleConnectionManager create(HttpClientConnectionManager manager, int timeToLive, TimeUnit unit) {
        return new IdleConnectionManager(manager, timeToLive, unit);
    }

}
